package com.doyutu.seed.config.shiro;

import java.io.Serializable;
import java.util.concurrent.TimeUnit;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.session.Session;
import org.apache.shiro.session.mgt.eis.EnterpriseCacheSessionDAO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.RedisTemplate;

/**
 * @author DoyuTu
 * @version 0.0.1
 * spring-boot-project-seed
 */
@Slf4j
public class RedisSessionDAO extends EnterpriseCacheSessionDAO {

    private static final int EXPIRE_TIME = 1800;

    private static final String PREFIX = "shiro:session-";

    @Autowired
    @Qualifier("shiroRedisTemplate")
    private RedisTemplate<String, Object> redisTemplate;

    @Override
    protected Serializable doCreate(Session session) {
        Serializable sessionId = super.doCreate(session);
        log.info("创建session：{}", sessionId.toString());
        redisTemplate.opsForValue().set(PREFIX + sessionId.toString(), session, EXPIRE_TIME, TimeUnit.SECONDS);
        return sessionId;
    }

    @Override
    protected Session doReadSession(Serializable sessionId) {
        if (sessionId == null) {
            return null;
        }
        log.info("读取session：{}", sessionId);
        Session session = super.doReadSession(sessionId);
        if (null == session) {
            session = (Session)redisTemplate.opsForValue().get(PREFIX + sessionId.toString());
        }
        return session;
    }

    @Override
    protected void doUpdate(Session session) {
        log.info("获取session：{}", session.getId().toString());
        super.doUpdate(session);
        final String key = PREFIX + session.getId().toString();
        Boolean hasKey = redisTemplate.hasKey(key);
        if (hasKey == null || !hasKey) {
            redisTemplate.opsForValue().set(key, session, EXPIRE_TIME, TimeUnit.SECONDS);
        }
    }

    @Override
    protected void doDelete(Session session) {
        if (session == null || session.getId() == null) {
            return;
        }
        log.info("删除session：{}", session.getId());
        super.doDelete(session);
        redisTemplate.delete(PREFIX + session.getId().toString());
    }
}
